package com.leetcode.No0004;

import org.junit.Test;

/**
 * @author Louzen
 */
public class Solution01 {

	public double findMedianSortedArrays(int[] nums1, int[] nums2) {

		int len1 = nums1.length;
		int len2 = nums2.length;
		int total = len1 + len2;
		// destination index
		int dstInd = total / 2;

		double ans = 0;

		int index1 = 0, index2 = 0;
		int preValue = 0, currentValue = 0;
		for(int i = 0; i <= dstInd; ++i) {
			preValue = currentValue;
			if(index1 < len1 && index2 < len2) {
				if (nums1[index1] < nums2[index2]) {
					currentValue = nums1[index1++];
				} else {
					currentValue = nums2[index2++];
				}
			} else if(index1 < len1) {
				currentValue = nums1[index1++];
			} else {
				currentValue = nums2[index2++];
			}
			if(i == dstInd){
				ans = currentValue;
			}
		}
		// 如果total是偶数
		if((total & 1) == 0) {
			ans = (ans + preValue) / 2;
		}

		return ans;
	}

	@Test
	public void test01(){
		int[] nums1 = new int[]{1,3};
		int[] nums2 = new int[]{2};

		System.out.println(findMedianSortedArrays(nums1, nums2));
	}

	@Test
	public void test02(){
		int[] nums1 = new int[]{1,3};
		int[] nums2 = new int[]{};

		System.out.println(findMedianSortedArrays(nums1, nums2));
	}

	@Test
	public void test03(){
		int[] nums1 = new int[]{1,2};
		int[] nums2 = new int[]{3,4};

		System.out.println(findMedianSortedArrays(nums1, nums2));
	}

}
